package top.so.controller;



import org.codehaus.jackson.map.ObjectMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.SessionAttributes;
import org.springframework.web.servlet.ModelAndView;

import top.so.dto.*;
import top.so.entity.ColumnArticle;
import top.so.service.*;

import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping("/myBlog")
@SessionAttributes("isSuccess")//操作状态
public class MyBlogController {

    @Autowired
    private BlogArticleService blogArticleService;
    @Autowired
    private DraftsService draftsService;
    @Autowired
    private BlogCollectionService blogCollectionService;
    @Autowired
    private ColumnService columnService;
    @Autowired
    private ColumnArticleService columnArticleService;


    @RequestMapping(value = "",method = RequestMethod.GET)
    public ModelAndView myBlog(HttpSession httpSession){
        ModelAndView mv = new ModelAndView("user/personalHomePage");
        UserDTO userDTO = (UserDTO) httpSession.getAttribute("currUser");
        BlogArticleDTO blogArticleDTO = new BlogArticleDTO();
        blogArticleDTO.setUserName(userDTO.getLoginName());
        List<BlogArticleDTO> blogArticleDTOList = blogArticleService.selectBlogArticleWithPage(blogArticleDTO,1);
        if(!blogArticleDTOList.isEmpty())
        mv.addObject("blogArticleDTOList",blogArticleDTOList);
        return mv;
    }

    /**
     * 跳转至用户草稿箱
     * @param httpSession
     * @return
     */
    @RequestMapping(value = "drafts",method = RequestMethod.GET)
    public ModelAndView drafts(HttpSession httpSession){
        ModelAndView mv = new ModelAndView("user/Drafts");
        UserDTO userDTO = (UserDTO) httpSession.getAttribute("currUser");
        DraftsDTO draftsDTO = new DraftsDTO();
        draftsDTO.setUserID(userDTO.getUserID());
        List<DraftsDTO> draftsDTOList = draftsService.selectWithPage(draftsDTO,1);
        if(!draftsDTOList.isEmpty()){
            mv.addObject("draftsDTOList",draftsDTOList);
        }
        return mv;
    }

    /**
     * 跳转至用户收藏博文
     * @param userID
     * @return
     */
    @RequestMapping(value = "collection",method = RequestMethod.GET)
    public ModelAndView collection(String userID){
        ModelAndView mv = new ModelAndView("user/Collection");
        BlogCollectionDTO blogCollectionDTO = new BlogCollectionDTO();
        blogCollectionDTO.setUserID(userID);
      List<BlogCollectionDTO> blogCollectionDTOList = blogCollectionService.selectWithPage(blogCollectionDTO,1);
      for(int i=0;i<blogCollectionDTOList.size();i++){
          if(blogCollectionDTOList.get(i).getArticleContent().length()>100){
              blogCollectionDTOList.get(i).setArticleContent(blogCollectionDTOList.get(i).getArticleContent().replaceAll("\\r|\\n","").replace(" ","").substring(1,100));
          }
      }
      if(!blogCollectionDTOList.isEmpty()){
          mv.addObject("blogCollectionDTOList",blogCollectionDTOList);
      }
        return mv;
    }

    @RequestMapping(value = "column",method = RequestMethod.GET)
    public ModelAndView column(HttpSession httpSession){
        ModelAndView mv = new ModelAndView("user/Column");
        ColumnDTO columnDTO = new ColumnDTO();
        UserDTO userDTO = (UserDTO) httpSession.getAttribute("currUser");
        columnDTO.setUserID(userDTO.getUserID());
        List<ColumnDTO> columnDTOList = columnService.selectWithPage(columnDTO,1);
        if(!columnDTOList.isEmpty())
        mv.addObject("columnDTOList",columnDTOList);
        return mv;
    }

    @RequestMapping(value = "goWriteBlog")
    public ModelAndView goWriteBlog(DraftsDTO draftsDTO,HttpSession httpSession){
        ModelAndView mv = new ModelAndView("user/writeBlog");
        UserDTO userDTO = (UserDTO) httpSession.getAttribute("currUser");
        ColumnDTO columnDTO = new ColumnDTO();
        columnDTO.setUserID(userDTO.getUserID());
        List<ColumnDTO> columnList = columnService.select(columnDTO);
        if(columnList!=null && !columnList.isEmpty()){
            mv.addObject("columnList",columnList);
        }
        if(draftsDTO.getDraftsID()!=null){
            List<DraftsDTO> draftsDTOList = draftsService.selectWithPage(draftsDTO,1);
            if(!draftsDTOList.isEmpty()){
                mv.addObject("draftsDTO",draftsDTOList.get(0));
            }
        }
        return mv;
    }



    /**
     * 发表文章
     * @param blogArticleDTO
     * @param httpSession
     * @return
     */
    @RequestMapping(value = "publishBlog",method = RequestMethod.POST,produces="application/json")
    @ResponseBody
    public String publishBlog(BlogArticleDTO blogArticleDTO,String columnID, HttpSession httpSession){
        String result = null;
        Map<String,Object> map = new HashMap<String,Object>();
       ObjectMapper mapper = new ObjectMapper();
        //从session中获取当前用户，并且赋值给文章作者
        UserDTO userDTO = (UserDTO) httpSession.getAttribute("currUser");
        blogArticleDTO.setUserName(userDTO.getLoginName());
        if(columnID.equals("无")){
            if(blogArticleService.insertBlogArticle(blogArticleDTO)){
                map.put("isSuccess","true");
            }
            else{
                map.put("isSuccess","false");
            }
        }
        else{
            ColumnArticle columnArticle = new ColumnArticle();
            columnArticle.setArticleName(blogArticleDTO.getArticleName());
            columnArticle.setArticleContent(blogArticleDTO.getArticleContent());
            columnArticle.setColumnID(columnID);
            if(columnArticleService.insertColumnArticle(columnArticle)){
                map.put("isSuccess","true");
            }
            else{
                map.put("isSuccess","false");
            }
        }

        try {
            result = mapper.writeValueAsString(map);
        } catch (IOException e) {
            e.printStackTrace();
        }

        return result;
    }

    @RequestMapping(value = "goEditArticle",method = RequestMethod.GET)
    public ModelAndView goEditArticle(BlogArticleDTO blogArticleDTO){
        ModelAndView mv = new ModelAndView("user/editBlog");
        List<BlogArticleDTO> blogArticleDTOList = blogArticleService.selectBlogArticleWithPage(blogArticleDTO,1);
        for(BlogArticleDTO blogArticle:blogArticleDTOList){
            BlogArticleDTO result = blogArticle;
            mv.addObject("blogArticleDTO",result);
            break;
        }
        return mv;
    }

    /**
     * 修改文章
     * @param blogArticleDTO
     * @return
     */
    @RequestMapping(value = "editArticle",method = RequestMethod.POST)
    @ResponseBody
    public String editArticle(BlogArticleDTO blogArticleDTO){
        String result = null;
        Map<String,Object> map = new HashMap<String,Object>();
        ObjectMapper mapper = new ObjectMapper();
        if(blogArticleService.updateBlogArticle(blogArticleDTO)){
            map.put("isSuccess","true");
        }
        else{
            map.put("isSuccess","false");
        }
        try {
            result = mapper.writeValueAsString(map);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return result;
    }

    /**
     * 删除文章
     */
    @RequestMapping(value = "deleteArticle",method = RequestMethod.POST)
    public ModelAndView deleteArticle(BlogArticleDTO blogArticleDTO, ModelMap modelMap){
        ModelAndView mv = new ModelAndView("redirect:/myBlog");
        if(blogArticleService.deleteBlogArticle(blogArticleDTO)){
           modelMap.addAttribute("isSuccess","true");
        }
        else{
            modelMap.addAttribute("isSuccess","false");
        }
        return mv;
    }

    @RequestMapping(value = "commentSwitch",method = RequestMethod.POST)
    public ModelAndView commentSwitch(BlogArticleDTO blogArticleDTO){
        ModelAndView mv = new ModelAndView("user/personalHomePage");
        System.out.println(blogArticleDTO.getCommentSwitch());
        blogArticleService.updateBlogArticle(blogArticleDTO);
        return mv;
    }






    @RequestMapping(value = "goPage",method = RequestMethod.POST)
    public ModelAndView goPage(int pageNum,HttpSession httpSession){
        UserDTO userDTO = (UserDTO) httpSession.getAttribute("currUser");
        ModelAndView mv = new ModelAndView("user/personalHomePage");
        BlogArticleDTO blogArticleDTO = new BlogArticleDTO();
        blogArticleDTO.setUserName(userDTO.getLoginName());
        List<BlogArticleDTO> blogArticleDTOList = blogArticleService.selectBlogArticleWithPage(blogArticleDTO,pageNum);
            mv.addObject("blogArticleDTOList",blogArticleDTOList);
        return mv;
    }



}
